package com.example.wblog.controller.admin;

import com.example.wblog.model.Article;
import com.example.wblog.model.ViewObject;
import com.example.wblog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping({"/admin/article"})
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @RequestMapping({"", "/", "/index"})
    String index() {
        return "redirect:/admin/article/page/1";
    }

    @RequestMapping({"page/{pageId}"})
    String page(Model model,
                @PathVariable("pageId") int pageId) {
        final int SIZE = 5;
        int offset = (pageId - 1) * SIZE;
        List<Article> articleList = articleService.selectList(offset, SIZE);
        model.addAttribute("article_list", articleList);
        return "admin/article";
    }

    @RequestMapping(value = {"edit"}, method = RequestMethod.GET)
    String edit() {
        return "admin/edit";
    }

    @RequestMapping(value = {"add"}, method = RequestMethod.POST)
    String add(@RequestParam("title") String title,
               @RequestParam("describes") String describes,
               @RequestParam("category") String category,
               @RequestParam("content") String content) {
        Article article = new Article().setTitle(title).setDescribes(describes).
                setCategory(category).setContent(content).setCommentCount(0).
                setCreatedDate(new Date());
        articleService.add(article);
        return "redirect:/admin/article";
    }

    @RequestMapping(value = {"remove/{articleId}"}, method = RequestMethod.GET)
    String remove(@PathVariable("articleId") int articleId) {
        articleService.deleteById(articleId);
        return "redirect:/admin/article";
    }
//
//    @RequestMapping(value = {"update"}, method = RequestMethod.POST)
//    String add() {
//        return
//    }
}
